package com.myzl.coal.python;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ArrayUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * @author Administrator
 */
@Slf4j(topic = "admin-user")
public class PythonInvokeUtils {

    public static List<String> invokeRelativeUrl(String name, String... args) {
        String path = System.getProperty("user.dir")+ File.separator +"python"+File.separator + name;
        List<String> list = invokePython(path, args);
        return list;
    }

    public static List<String> invokePython(String path, String... args) {
        try {
            String exe;
            if(FileUtil.isWindows()){
                exe = "D://software//python3.9.10//python.exe";
            }else {
                exe = "python3";
            }
            String[] cmdArr = new String[]{exe, path};
            if (ArrayUtil.isNotEmpty(args)) {
                cmdArr = ArrayUtil.addAll(cmdArr, args);
            }
            Arrays.stream(cmdArr).forEach(log::info);
            Process process = Runtime.getRuntime().exec(cmdArr);
            List<String> logList = new ArrayList<>();
            IoUtil.readLines(process.getInputStream(), Charset.defaultCharset(), logList);
            logList.forEach(log::info);
            return logList;
        } catch (Exception e) {
            log.info("执行python脚本错误:", e);
        }
        return Collections.emptyList();
    }
}
